<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="班次编码" prop="shiftCode">
              <el-input v-model="formData.shiftCode" placeholder="请输入班次编码" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班次名称" prop="shiftName">
              <el-input v-model="formData.shiftName" placeholder="请输入班次名称" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="班次开始时间" prop="shiftStartTime">
              <el-time-picker clearable v-model="formData.shiftStartTime" format="HH:mm:ss" value-format="HH:mm:ss"
                              placeholder="选择班次开始时间" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班次结束时间" prop="shiftEndTime">
              <el-time-picker clearable v-model="formData.shiftEndTime" format="HH:mm:ss" value-format="HH:mm:ss"
                              placeholder="选择班次结束时间" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="班次总时长(min)" prop="shiftTotalTime">
              <el-input v-model="formData.shiftTotalTime" placeholder="自动计算" readonly style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio v-for="dict in getDictDatas(DICT_TYPE.COMMON_STATUS)" :key="dict.value" :label="Number(dict.value)">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划停机时间(min)" prop="planStopTime">
              <el-input v-model.number="formData.planStopTime" placeholder="请输入计划停机时间" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划休息时间(min)" prop="planRestTime">
              <el-input v-model.number="formData.planRestTime" placeholder="请输入计划休息时间" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" :rows="3" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as ShiftApi from '@/api/system/shift';
import {getDictDatas, getDictDataLabel, DICT_TYPE} from '@/utils/dict'

export default {
  name: "ShiftForm",
  components: {},
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        shiftCode: undefined,
        shiftName: undefined,
        shiftStartTime: undefined,
        shiftEndTime: undefined,
        shiftTotalTime: undefined,
        remark: undefined,
        planStopTime: undefined,
        planRestTime: undefined,
        status: 1,
      },
      // 表单校验
      formRules: {
        shiftCode: [
          { required: true, message: '班次编码不能为空', trigger: 'blur' }
        ],
        shiftName: [
          { required: true, message: '班次名称不能为空', trigger: 'blur' }
        ],
        shiftStartTime: [
          { required: true, message: '班次开始时间不能为空', trigger: 'blur' }
        ],
        shiftEndTime: [
          { required: true, message: '班次结束时间不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'change' }
        ]
      },
    };
  },
  watch: {
    // 监听开始时间和结束时间变化，计算总时长
    'formData.shiftStartTime': function() {
      this.calculateTotalTime();
    },
    'formData.shiftEndTime': function() {
      this.calculateTotalTime();
    }
  },
  methods: {
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await ShiftApi.getShift(id);
          this.formData = res.data;
          this.dialogTitle = "编辑班次";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增班次";
      }
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await ShiftApi.updateShift(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await ShiftApi.createShift(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        shiftCode: undefined,
        shiftName: undefined,
        shiftStartTime: undefined,
        shiftEndTime: undefined,
        shiftTotalTime: undefined,
        remark: undefined,
        planStopTime: undefined,
        planRestTime: undefined,
        status: 1,
      };
      this.resetForm("formRef");
    },
    /** 计算班次总时长 */
    calculateTotalTime() {
      if (this.formData.shiftStartTime && this.formData.shiftEndTime) {
        const [startHours, startMinutes, startSeconds] = this.formData.shiftStartTime.split(':').map(Number);
        const [endHours, endMinutes, endSeconds] = this.formData.shiftEndTime.split(':').map(Number);

        // 计算开始时间的总分钟数
        const startTotalMinutes = startHours * 60 + startMinutes + startSeconds / 60;
        // 计算结束时间的总分钟数
        const endTotalMinutes = endHours * 60 + endMinutes + endSeconds / 60;

        // 如果结束时间小于开始时间，认为是跨天
        let totalMinutes;
        if (endTotalMinutes < startTotalMinutes) {
          totalMinutes = endTotalMinutes + 24 * 60 - startTotalMinutes;
        } else {
          totalMinutes = endTotalMinutes - startTotalMinutes;
        }

        this.formData.shiftTotalTime = Math.round(totalMinutes);
      }
    }
  }
};
</script>
